<template>
  <!-- <div>
    <el-dialog
      ref="refDlg"
      title="日常评估记录详情"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="clearForm"
      width="800px"
      @close="closeDialog"
    > -->
  <!-- <div> -->
  <div v-if="dialogShow">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>施工单位管理</el-breadcrumb-item>
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">日常考核</el-breadcrumb-item>
        <el-breadcrumb-item>新增</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="top-btn-group">
        <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
        <el-button size="mini" @click="handleBack">返回</el-button>
      </div>
    </div>
    <div>
      <el-form ref="refForm" class="financeForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="施工单位:" prop="unitCode">
              <span>{{ formData.unitName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考核日期:" prop="createTime">
              <span>{{ createTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-button type="primary" size="mini" @click="handleAddType">选择考核类别</el-button>
      <el-button size="mini" @click="handleDelType">取消考核类别</el-button>
    </div>
    <el-table
      ref="refTable"
      v-loading="tableLoading"
      element-loading-text="加载中"
      :data="tableData"
      :span-method="objectSpanMethod"
      border
      highlight-current-row
      :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
      style="width: 100%; margin-top: 20px"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="scoreType" label="考核类别" min-width="100" />
      <el-table-column prop="totalScore" label="考核总分" min-width="150" />
      <el-table-column prop="scoreDesc" label="考核说明" show-overflow-tooltip min-width="150" />
      <el-table-column prop="validStartTime" label="评分有效开始日期" min-width="250">
        <template slot="header">
          <span style="color: red">*</span>评分有效开始日期
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.dataId">{{ scope.row.validStartTime }}</span>
          <el-date-picker
            v-else
            v-model="scope.row.validStartTime"
            value-format="yyyy-MM-dd"
            align="right"
            type="date"
            placeholder="选择日期"
            size="mini"
            :picker-options="pickerOptions"
            @change="changeTime(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="validEndTime" label="评分有效截止日期" min-width="250">
        <template slot="header">
          <span style="color: red">*</span>评分有效截止日期
        </template>
        <template slot-scope="scope">
          <span v-show="scope.row.dataId">{{ scope.row.validEndTime }}</span>
          <el-date-picker
            v-show="!scope.row.dataId"
            v-model="scope.row.validEndTime"
            value-format="yyyy-MM-dd"
            align="right"
            type="date"
            placeholder="选择日期"
            size="mini"
            :picker-options="pickerOptions"
            @change="changeTime(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="detailItem" label="考核明细项目" min-width="200" />
      <el-table-column prop="grading" label="评分标准" min-width="150" />

      <el-table-column prop="scoreDesc" label="评分说明" show-overflow-tooltip min-width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.dataId">{{ scope.row.itemScoreDesc }}</span>
          <el-input v-else ref="itemScoreDesc" v-model="scope.row.itemScoreDesc" size="mini" placeholder="请输入评分说明" />
        </template>
      </el-table-column>

      <el-table-column prop="actualScore" label="实际得分" min-width="150">
        <template slot="header">
          <span style="color: red">*</span>实际得分
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.dataId">{{ scope.row.actualScore }}</span>
          <el-input v-else ref="actualScore" v-model.number="scope.row.actualScore" size="mini" placeholder="请输入实际得分" @blur="checkActualScore(scope.row)" />
        </template>
      </el-table-column>

      <!-- <el-table-column prop="usePosition" label="评估日期" min-width="150" :formatter="formatUsePosition" /> -->
    </el-table>
    <!-- </div> -->
    <add-score-type v-if="showAddTypeDlg" ref="ScoreCriteriaDlg" :visible.sync="showAddTypeDlg" @addType="handleGetType" />
  </div>
  <!-- <div slot="footer">
        <el-button size="mini" @click="closeDialog">返回</el-button>
        <el-button size="mini" type="primary" @click="submitForm">保存</el-button> -->
  <!-- </div>
    </el-dialog>
  </div> -->
</template>

<script>
import { queryDailyAssessment, saveDailyAssessment } from '@/api/constructionUnitMng'
import addScoreType from './addScoreType.vue'
export default {
  name: 'AddDailyRecord',
  components: { addScoreType },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      createTime: '',
      showAddTypeDlg: false,
      tableLoading: false,
      formData: {},
      tableData: [],
      selectedRows: [],
      allTableData: [],
      getNewData: [],
      pickerOptions: {
        disabledDate(time) {
          var date = new Date()
          var y = date.getFullYear()
          var m = date.getMonth() + 1
          var d = date.getDate()
          var nowTime = new Date(`${y}-${m}-${d} 00:00:00`)
          return time.getTime() < nowTime.getTime()
        }
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 选中行id
    selectedIds() {
      return this.selectedRows.map(row => {
        return row.scoreCriteriaId
      })
    }
  },
  created() {
    this.tableLoading = true
    this.createTime = this.getNowTime()
    this.formData = this.detailData.data
    const otherFilter = [{ 'id': 'unitCode', 'property': 'unitCode', 'operator': '=', 'value': this.formData.unitCode }]
    const obj = { 'scoreNature': 'DAILY' }
    const formData = new FormData()
    formData.append('filtersRaw', JSON.stringify(otherFilter))
    formData.append('paramsRaw', JSON.stringify(obj))
    queryDailyAssessment(formData).then(res => {
      if (res.success && res.data && res.data.length) {
        this.allTableData = res.data
        this.allTableData.forEach(item => {
          item.dailyAssessDetailDTOS = item.assessDetailsDtos
          // delete item.assessDetailsDtos
        })
        const arr = []
        res.data.forEach(row => {
          if (row.assessDetailsDtos && row.assessDetailsDtos.length) {
            row.assessDetailsDtos.forEach((item, index) => {
              const obj = {}
              obj.dataId = row.id
              obj.scoreCriteriaId = row.scoreCriteriaId
              obj.scoreType = row.scoreType
              obj.totalScore = row.totalScore
              obj.scoreDesc = row.scoreDesc
              obj.validStartTime = row.validStartTime.split(' ')[0]
              obj.validEndTime = row.validEndTime.split(' ')[0]
              obj.actualScore = row.actualScore
              obj.itemScoreDesc = item.scoreDesc
              obj.detailItem = item.detailItem
              obj.grading = item.grading
              if (index === 0) {
                obj.spanIndex = row.assessDetailsDtos.length
              }
              arr.push(obj)
            })
          }
        })
        this.tableData = arr
      }
      this.tableLoading = false
    })
  },
  activated() {},
  methods: {
    /**
     * 表格合并
     * @param {*} param0
     * row 表格每一行的数据
     * column 表格每一列的数据
     * rowIndex 表格的行索引,不包括表头,从0开始
     * columnIndex 表格的列索引,从0开始
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <= 5 || columnIndex === 9) {
        // 过滤需要合并的行数
        if (row.spanIndex) {
          // 若rowIndex存在，则合并
          return {
            rowspan: row.spanIndex,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    getNowTime() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}年${month}月${day}日`
    },
    // 新增
    handleAddType() {
      this.showAddTypeDlg = true
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    handleGetType(data) {
      if (data && data.length) {
        if (!this.tableData.length) {
          data.forEach(row => {
            if (row.configScoreDetailDTOS && row.configScoreDetailDTOS.length) {
              row.configScoreDetailDTOS.forEach((item, index) => {
                const obj = {}
                obj.itemId = item.id
                obj.scoreCriteriaId = row.id
                obj.scoreType = row.scoreType
                obj.totalScore = row.totalScore
                obj.scoreDesc = row.scoreDesc
                obj.detailItem = item.detailItem
                obj.grading = item.grading
                this.$set(obj, 'validStartTime', '')
                this.$set(obj, 'validEndTime', '')
                this.$set(obj, 'actualScore', '')
                this.$set(obj, 'itemScoreDesc', '')
                if (index === 0) {
                  obj.spanIndex = row.configScoreDetailDTOS.length
                }
                this.tableData.push(obj)
                this.getNewData.push(obj)
              })
            } else {
              const obj = {}
              // obj.itemId = item.id
              obj.scoreCriteriaId = row.id
              obj.scoreType = row.scoreType
              obj.totalScore = row.totalScore
              obj.scoreDesc = row.scoreDesc
              this.tableData.push(obj)
            }
          })
          return
        }
        const arr1 = []
        const arr2 = []
        data.forEach(row => {
          const flag = this.tableData.some(v => v.scoreCriteriaId === row.id)
          if (flag) {
            arr1.push(row)
          } else {
            if (row.configScoreDetailDTOS && row.configScoreDetailDTOS.length) {
              row.configScoreDetailDTOS.forEach((item, index) => {
                const obj = {}
                obj.itemId = item.id
                obj.scoreCriteriaId = row.id
                obj.scoreType = row.scoreType
                obj.totalScore = row.totalScore
                obj.scoreDesc = row.scoreDesc
                obj.detailItem = item.detailItem
                obj.grading = item.grading
                this.$set(obj, 'validStartTime', '')
                this.$set(obj, 'validEndTime', '')
                this.$set(obj, 'actualScore', '')
                this.$set(obj, 'itemScoreDesc', '')
                if (index === 0) {
                  obj.spanIndex = row.configScoreDetailDTOS.length
                }
                arr2.push(obj)
              })
            } else {
              const obj = {}
              // obj.itemId = item.id
              obj.scoreCriteriaId = row.id
              obj.scoreType = row.scoreType
              obj.totalScore = row.totalScore
              obj.scoreDesc = row.scoreDesc
              obj.spanIndex = 1
              this.tableData.push(obj)
            }
          }
        })
        if (arr1.length) {
          const msgArr = arr1.map(m => m.scoreType)
          this.$message.warning(`【${msgArr.toString()}】考核类别已存在`)
        }
        this.tableData = [...this.tableData, ...arr2]
        this.getNewData = [...this.getNewData, ...arr2]
      }
    },
    // 取消选择
    handleDelType() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择【取消考核类别】项')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableData.length === this.selectedRows.length) {
          this.tableData = []
          this.allTableData = []
          this.getNewData = []
          return
        }
        const tmpData1 = this.tableData.filter(row => {
          const index = this.selectedRows.findIndex(v => v.scoreCriteriaId === row.scoreCriteriaId)
          return index === -1
        })
        const tmpData2 = this.allTableData.filter(row => {
          const index = this.selectedRows.findIndex(v => v.scoreCriteriaId === row.scoreCriteriaId)
          return index === -1
        })
        const tmpData3 = this.getNewData.filter(row => {
          const index = this.selectedRows.findIndex(v => v.scoreCriteriaId === row.scoreCriteriaId)
          return index === -1
        })
        this.tableData = tmpData1
        this.allTableData = tmpData2
        this.getNewData = tmpData3
        this.selectedRows = []
        this.$refs.refTable.clearSelection()
        // this.allTableData.forEach((item, index) => {
        //   // item.spanIndex = item.assessDetailsDtos.length
        //   this.selectedRows.forEach(select => {
        //     if (item.scoreCriteriaId === select.scoreCriteriaId) {
        //       this.allTableData.splice(index, 1)
        //     }
        //   })
        // })
      })
    },
    // 校验实际得分
    checkActualScore(row) {
      if (row.actualScore > row.totalScore) {
        this.$message.warning('实际得分不能大于总分值，请重新输入')
        row.actualScore = ''
      } else if (row.actualScore < 0) {
        this.$message.warning('实际得分不能小于零，请重新输入')
        row.actualScore = ''
      }
    },
    changeTime(row) {
      if (row.validStartTime && row.validEndTime && row.validStartTime > row.validEndTime) {
        this.$message.warning('评分有效截止日期不能早于评分有效开始日期，请重新选择')
        row.validStartTime = ''
        row.validEndTime = ''
      }
    },
    // 关闭弹窗
    handleBack() {
      this.dialogShow = false
      this.clearForm()
      this.$emit('success')
    },
    // 关闭弹窗前的回调
    clearForm(done) {
      this.queryObj = {
        id: null
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 保存
    handleSave() {
      if (!this.tableData.length) {
        this.$message.warning('请选择考核类别')
        return
      }
      let tableArr = []
      this.getNewData.forEach((item) => {
        const obj = item
        obj.dailyAssessDetailDTOS = []
        const itemObj = {
          scoreDetailId: item.itemId,
          scoreDesc: item.itemScoreDesc
        }
        obj.dailyAssessDetailDTOS.push(itemObj)
        if (!tableArr.length) {
          tableArr.push(obj)
        } else {
          const flag = tableArr.some(v => v.scoreType === item.scoreType)
          if (flag) {
            tableArr.forEach(m => {
              if (m.scoreType === item.scoreType) {
                m.dailyAssessDetailDTOS.push(itemObj)
              }
            })
          } else {
            tableArr.push(obj)
          }
        }
      })
      tableArr.forEach(item => {
        // item.scoreDesc = item.outsScoreDesc
        item.unitCode = this.formData.unitCode
        item.validStartTime = item.validStartTime + ' ' + '00:00:00'
        item.validEndTime = item.validEndTime + ' ' + '00:00:00'
      })
      tableArr = [...this.allTableData, ...tableArr]
      const tableFlag = tableArr.some(item => !item.validStartTime.length || !item.validEndTime.length || !item.actualScore)
      if (tableFlag) {
        this.$message.warning('请完善表格数据')
        return
      }
      this.$confirm('提交后，将更新现有评估结果，是否确认？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        saveDailyAssessment(tableArr).then(res => {
          if (res.success) {
            this.$message.success('操作成功')
            this.handleBack()
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
